package com.iaiai.browser.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.iaiai.browser.activity.database.DatabaseOpenHelper;
import com.iaiai.browser.activity.entiry.Favorites;
import com.iaiai.browser.activity.widget.FavoritePanel;
import com.iaiai.browser.activity.widget.LabelManager;
import com.iaiai.browser.activity.widget.WebManager;
import com.iaiai.browser.core.util.AnimationUtil;

public class MainActivity extends Activity {

	private DatabaseOpenHelper databaseOpenHelper;

	private ProgressDialog loadingDialog; // loading

	private LinearLayout favoriteLayout; // 收藏布局

	private HorizontalScrollView menuLayout; // 底部菜单布局

	private WebManager webManager; // 控件管理

	private ImageView favorites; // 收藏
	private ImageView favoritesGray; // 收藏

	private ImageView reload; // 刷新
	private ImageView reloadGray; // 刷新

	private ImageView forward; // 向前
	private ImageView forwardGray; // 向前

	private ImageView back; // 向后
	private ImageView backGray;

	private ImageView history; // 历史记录
	private LinearLayout historyLayout; // 历史记录

	private ImageView about; // 关于
	private LinearLayout aboutLayout; // 关于

	private ImageView upgrade; // 升级
	private LinearLayout upgradeLayout; // 升级

	private ImageView home; // home

	private void init() {
		databaseOpenHelper = new DatabaseOpenHelper(this);

		favoriteLayout = (LinearLayout) findViewById(R.id.favoriteLayout);
		menuLayout = (HorizontalScrollView) findViewById(R.id.menuLayout);
		favorites = (ImageView) findViewById(R.id.favorites);
		reload = (ImageView) findViewById(R.id.reload);
		forward = (ImageView) findViewById(R.id.forward);
		back = (ImageView) findViewById(R.id.back);
		history = (ImageView) findViewById(R.id.history);
		about = (ImageView) findViewById(R.id.about);
		upgrade = (ImageView) findViewById(R.id.upgrade);
		historyLayout = (LinearLayout) findViewById(R.id.historyLayout);
		aboutLayout = (LinearLayout) findViewById(R.id.aboutLayout);
		upgradeLayout = (LinearLayout) findViewById(R.id.upgradeLayout);
		home = (ImageView) findViewById(R.id.home);
		backGray = (ImageView) findViewById(R.id.backGray);
		favoritesGray = (ImageView) findViewById(R.id.favoritesGray);
		reloadGray = (ImageView) findViewById(R.id.reloadGray);
		forwardGray = (ImageView) findViewById(R.id.forwardGray);

		loadingDialog = new ProgressDialog(this);
		loadingDialog.setMessage("Loading...");
		// loadingDialog.setCancelable(false);

		webManager = new WebManager(this);
		webManager.setHandler(new WebManager.Hander() {
			public void loading() {
				loadingDialog.show();
			}

			public void unLoading() {
				loadingDialog.cancel();
			}

			public void open(String url) {
				databaseOpenHelper.insertHistory(url); // 添加历史记录

				closeMenu();

				menuOperate(true); // 菜单可操作
			}

			public void selected(int index) {
				menuOperate(true); // 菜单可操作
			}

			public void showIndex() {
				menuOperate(false);	//菜单变灰
			}
		});

		favorites.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				closeMenu();
				
				loadingDialog.show();	//显示loading...
				
				final android.os.Handler handler = new android.os.Handler();
				new Thread() {
					public void run() {
						final String title = webManager.getSelTitle();
						final String url = webManager.getSelUrl();
						final Bitmap bitmap = webManager.getSelScreen();

						if (title == null || url == "") {
							return;
						}
						
						handler.post(new Runnable() {
							public void run() {
								if (databaseOpenHelper.queryFavoritesByTitle(title)) {
									loadingDialog.dismiss();	//隐藏loading...
									Toast.makeText(MainActivity.this, "收藏里以经有此标题，添加失败!", Toast.LENGTH_LONG).show();
									return;
								}
								if (databaseOpenHelper.queryFavoritesByUrl(url)) {
									loadingDialog.dismiss();	//隐藏loading...
									Toast.makeText(MainActivity.this, "收藏里以经有此地址，添加失败!", Toast.LENGTH_LONG).show();
									return;
								}

								databaseOpenHelper.insertFavorites(title, url, saveScreen(bitmap));
								
								loadingDialog.dismiss();	//隐藏loading...
								Toast.makeText(MainActivity.this, "添加成功!", Toast.LENGTH_LONG).show();
								
								refFavorite(); // 刷新收藏
							}
						});
					}
				}.start();
			}
		});

		reload.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				closeMenu();

				webManager.ref();
			}
		});

		forward.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				closeMenu();

				webManager.goForward();
			}
		});

		back.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				closeMenu();

				webManager.goBack();
			}
		});

		history.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				closeMenu();

				Intent it = new Intent(MainActivity.this, HistoryActivity.class);
				startActivityForResult(it, 0);
			}
		});

		about.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				closeMenu();

				showAbout(); // 显示关于
			}
		});

		upgrade.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				closeMenu();
			}
		});

		home.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				webManager.showHome();

				menuOperate(false); // 菜单不可操作
			}
		});
	}

	/**
	 * 保存图片
	 * @param bitmap
	 * @return 返回文件全路径
	 */
	private String saveScreen(Bitmap bitmap) {
		if (bitmap == null)
			return null;
		
		String folder = null;
		
		if(sdCardIsExsit()){		//SD卡已经成功挂载
			folder = Environment.getExternalStorageDirectory().getAbsolutePath()+"/browser-iaiai/screen/";//你的SD卡路径
		}else{//你的本地路径
			folder = getFilesDir().toString()+"/screen/";
		}
		
		if(folder==null)return null;
		
		new File(folder).mkdirs();
		String filename = getUUID();	//文件名
		
		try {
			FileOutputStream fos = new FileOutputStream(folder+filename);
			bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return folder+filename;
	}
	
	/**
	 * 获得UUID
	 * @return
	 */
	private String getUUID(){
		return UUID.randomUUID().toString();
	}
	
	/**
	 * 判断sdcard是否已安装
	 * 
	 * @return true安装，false未安装
	 */
	private boolean sdCardIsExsit() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	/**
	 * 关闭菜单
	 */
	private void closeMenu() {
		if (menuLayout.getVisibility() == View.VISIBLE) {
			menuLayout.startAnimation(AnimationUtil.getContactSearchClose(MainActivity.this));
			menuLayout.setVisibility(View.GONE);
		}
	}

	/**
	 * 显示关于
	 */
	private void showAbout() {
		new AlertDialog.Builder(this).setTitle("关于").setIcon(R.drawable.about)
				.setPositiveButton(android.R.string.ok, null).setMessage("浏览器 - 丸子\r\n\r\n版本:1.1\r\nQQ:176291935")
				.show();
	}

	/**
	 * 显示菜单
	 * 
	 * @param bol
	 *            true显示，false灰色菜单
	 */
	private void menuOperate(boolean bol) {
		if (!bol) {
			backGray.setVisibility(View.VISIBLE);
			favoritesGray.setVisibility(View.VISIBLE);
			reloadGray.setVisibility(View.VISIBLE);
			forwardGray.setVisibility(View.VISIBLE);

			back.setVisibility(View.GONE);
			favorites.setVisibility(View.GONE);
			reload.setVisibility(View.GONE);
			forward.setVisibility(View.GONE);
		} else {
			backGray.setVisibility(View.GONE);
			favoritesGray.setVisibility(View.GONE);
			reloadGray.setVisibility(View.GONE);
			forwardGray.setVisibility(View.GONE);

			back.setVisibility(View.VISIBLE);
			favorites.setVisibility(View.VISIBLE);
			reload.setVisibility(View.VISIBLE);
			forward.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_MENU: // 菜单键
			if (menuLayout.getVisibility() == View.GONE) {
				menuLayout.startAnimation(AnimationUtil.getContactSearchOpen(this));
				menuLayout.setVisibility(View.VISIBLE);
			} else {
				menuLayout.startAnimation(AnimationUtil.getContactSearchClose(this));
				menuLayout.setVisibility(View.GONE);
			}
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			Bundle b = data.getExtras();
			webManager.open(b.getString("url"));
			break;
		}
	}

	/**
	 * 刷新收藏
	 */
	private void refFavorite() {
		favoriteLayout.removeAllViews();

		List<Favorites> list = databaseOpenHelper.queryFavorites();
		if (list == null || list.size() <= 0) {
			favoriteLayout.addView(new FavoritePanel(this).getWidget("无", null));
		}
		for (final Favorites favorite : list) {
			final LinearLayout ly = new FavoritePanel(this).getWidget(favorite.getName(), favorite.getCreateDate(),favorite.getFilename());
			ly.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					webManager.open(favorite.getUrl());
				}
			});
			ly.setOnLongClickListener(new OnLongClickListener() {
				public boolean onLongClick(View v) {
					AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
					builder.setTitle("菜单");
					builder.setItems(new CharSequence[] { "删除" }, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int item) {
							databaseOpenHelper.deleteFavorites(favorite.getId()); // 删除
							favoriteLayout.removeView(ly);
							
							if(favorite.getFilename()!=null)
								new File(favorite.getFilename()).delete();	//删除文件

							refFavorite(); // 刷新收藏
						}
					});
					builder.create().show();

					return false;
				}
			});
			favoriteLayout.addView(ly);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		init();

		refFavorite(); // 刷新收藏
	}
}